<template>
  <el-row class="form_filter" :gutter="40">
    <el-form ref="formFilter" :label-width="`${labelWidth}px`" :rules="rules" :model="formParams">
      <el-col v-for="(item, index) of items" :key="index" :span="item.span">
        <el-form-item :label="item.label" :prop="item.key" :class="{'datePicker' : item.type === 'datePicker'}">
          <span v-if="item.type === 'span'">{{ formParams[item.key] }}</span>
          <el-input
            v-if="item.type === 'input'"
            v-model="formParams[item.key]"
            size="small"
            :disabled="item.disabled"
            :placeholder="`请输入${item.placeholder ? item.placeholder : item.label}`"
          />
          <el-input
            v-if="item.type === 'phone'"
            v-model="formParams[item.key]"
            size="small"
            type="number"
            :disabled="item.disabled"
            :placeholder="`请输入${item.placeholder ? item.placeholder : item.label}`"
          />
          <el-radio-group v-if="item.type === 'radio'" v-model="formParams[item.key]">
            <el-radio v-for="(item1, idx) in item.radioGroup" :key="idx" :label="item1.label">{{ item1.value }}</el-radio>
          </el-radio-group>
          <el-select v-if="item.type === 'select'" v-model="formParams[item.key]">
            <el-option
              v-for="item1 in item.selectGroup"
              :key="item1.value"
              :value="item1.value"
              :label="item1.label"
            />
          </el-select>
          <el-select
            v-if="item.type === 'remote'"
            v-model="formParams[item.key]"
            :multiple="item.multiple"
            filterable
            remote
            reserve-keyword
            :placeholder="item.placeholder || '请输入'"
            :remote-method="(query)=>{ remoteMethod(query,item) }"
            :loading="remoteLoading"
          >
            <el-option
              v-for="(v, idx) in remoteOptions"
              :key="idx"
              :label="v[item.key]"
              :value="v.resultValue"
            />
          </el-select>
          <el-date-picker
            v-if="item.type === 'datePicker'"
            v-model="formParams[item.key]"
            type="daterange"
            :value-format="item.valueFormat ? item.valueFormat : 'timestamp'"
            :format="`${item.format ? item.format : 'yyyy-MM-dd'}`"
            :range-separator="`${item.separator ? item.separator : '至'}`"
            :start-placeholder="`${item.startPlaceholder ? item.startPlaceholder : '开始日期'}`"
            :end-placeholder="`${item.endPlaceholder ? item.endPlaceholder : '结束日期'}`"
          />
          <el-checkbox v-if="item.checkbox" v-model="formParams[item.key2]">{{ item.text }}</el-checkbox>
          <AddressCascader v-if="item.type === 'address'" v-model="formParams[item.key]" :default-data.sync="formParams[item.key]" />
          <UploadImage v-if="item.type === 'uploadImg'" v-model="formParams[item.key]" :default-data.sync="formParams[item.hxKey]" />
          <div v-if="item.type === 'imgGroup'" class="_img_group">
            <UploadImage
              v-for="(item1, index1) in item.imgGroup"
              :key="index1"
              v-model="formParams[item.key][index1][item1.key]"
              :default-data.sync="formParams[item.key][index1][item1.hxKey]"
              :upload-tips="item1.uploadTips"
              :tips="item1.tips"
              :single="item.single"
            />
          </div>
          <Cascader v-if="item.type === 'cascader'" v-model="formParams[item.key]" :default-data.sync="formParams[item.key]" :req-opt="item" />
        </el-form-item>
      </el-col>
    </el-form>
  </el-row>
</template>
<script>
import AddressCascader from '@/components/Address/cascader'
import UploadImage from '@/components/UploadImage'
import Cascader from '@/components/Cascader'
import request from '@/utils/request'
export default {
  name: 'FormFilter',
  components: { AddressCascader, UploadImage, Cascader },
  props: {
    // 双向绑定数据对象
    formParams: {
      type: Object,
      default: () => {}
    },
    // 列表渲染数据
    items: {
      type: Array,
      default: () => []
    },
    labelWidth: {
      type: Number,
      default: 140
    },
    // 校验表单标示
    checkSubmit: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    // 设置校验规则(可自定义)
    var rules = {}
    this.items.forEach(item => {
      if (item.validate) {
        var validateFun = (rules, value, callback) => {
          if (!value) {
            if (item.type === 'radio') {
              return callback(new Error(`尚未选择${item.label}`))
            } else {
              return callback(new Error(`${item.label}不能为空`))
            }
          }
        }
        rules[item.key] = [
          {
            required: true,
            validator: typeof (item.validate) === 'function' ? item.validate : validateFun,
            trigger: item.trigger ? item.trigger : 'blur'
          }
        ]
      }
    })
    return {
      remoteLoading: false, // 联想搜索框loading
      remoteOptions: [], // 联想搜索的结果
      rules: rules
    }
  },
  watch: {
    checkSubmit(value) {
      if (value) {
        this.$refs.formFilter.validate()
      }
    }
  },
  methods: {
    // 联想搜索
    async remoteMethod(query, params) {
      console.log(query, 'query')
      console.log(params, 'params')
      this.remoteOptions = await this.requestApi(params, query)
      this.remoteOptions.forEach(item => {
        item.resultValue = `${item[params.value]}&&&${item[params.key]}`
      })
    },
    // 请求接口封装成动态接收api地址
    async requestApi(params, query) {
      const { url, searchKey, resultKey, contentType } = params
      const reqOpt = url.split('|')
      const [method, _url] = reqOpt[1] ? reqOpt : ['post', reqOpt[0]]
      const reqKey = method.toLowerCase() === 'post' ? 'data' : 'params'
      const requestParams = { pageFlag: false }
      requestParams[searchKey] = query
      const res = await request({
        url: _url,
        method,
        [reqKey]: requestParams,
        headers: {
          'Content-Type': contentType
        }
      })
      return res[resultKey]
    }
  }
}
</script>
<style lang="scss">
.form_filter {
  ._img_group {
    display: flex;
    width: 106%;
    justify-content: space-between;
    ._upload_img {
      margin-right: 50px;
    }
  }
  .el-date-editor--daterange.el-input__inner {
    width: 100%;
    height: 32px;
  }
  .el-select .el-input__inner{
    height: 32px;
  }
  .el-input--medium .el-input__icon {
    height: 32px;
    line-height: 32px;
  }
  .datePicker {
    .el-form-item__content {
      display: flex;
    }
    .el-checkbox {
      margin-left: 40px;
    }
  }
}
</style>
